package com.ruoyi.syf.TCPSocket;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.syf.domain.TCPSocketEscalationData;
import com.ruoyi.syf.domain.TCPSocketEscalationDataRes;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

public class SocketService {
    private static final int PORT = 12345;

    public static void main(String[] args) throws IOException {
        service();
    }

    public static void service() throws IOException {
        Selector selector = Selector.open();
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        serverChannel.socket().bind(new InetSocketAddress(PORT));
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            selector.select();
            Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
            while (keys.hasNext()) {
                SelectionKey key = keys.next();
                keys.remove();

                if (key.isAcceptable()) {
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    SocketChannel client = server.accept();
                    client.configureBlocking(false);
                    client.register(selector, SelectionKey.OP_READ);
                    System.out.println("新客户端已连接: " + client.getRemoteAddress());
                }

                if (key.isReadable()) {
                    SocketChannel client = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int bytesRead = client.read(buffer);
                    if (bytesRead > 0) {
                        buffer.flip();
                        byte[] data = new byte[bytesRead];
                        buffer.get(data);
                        String message = new String(data, StandardCharsets.UTF_8);
                        System.out.println("收到: " + message);

                        //处理接受数据并构建返回数据
                        TCPSocketEscalationDataRes dataRes = handlerMessage(message);

                        System.out.println("返回: " + JSON.toJSONString(dataRes));
                        ByteBuffer responseBuffer = ByteBuffer.wrap((JSON.toJSONString(dataRes) + "\n").getBytes(StandardCharsets.UTF_8));
                        client.write(responseBuffer);
                    }
                }
            }
        }
    }

    /**
     * 处理接受数据并构建返回数据
     */
    public  static TCPSocketEscalationDataRes handlerMessage(String message) {
        TCPSocketEscalationDataRes dataRes = new TCPSocketEscalationDataRes();
        //校验数据格式
        if (message.length() <3 || message.endsWith("@@")){
            dataRes.setSuccess(false);
            dataRes.setCode("10003");
            dataRes.setMessage("数据格式错误");
            return dataRes;
        }
        String substring = message.substring(0, message.length() - 4);
        TCPSocketEscalationData escalationData = JSONObject.parseObject(substring, TCPSocketEscalationData.class);

        //校验appId和serviceId
        //10001,appId不通过
        //10002,serviceId不通过
        dataRes.setDataId(escalationData.getDataId());
        dataRes.setServiceId(escalationData.getServiceId());

        //校验数据内容
        //10004,数据解密失败
        //10005,数据格式错误

        //校验数据签名
        //10006,数据签名错误
        //10007,数据签名过期

        //10009,其它

        dataRes.setSuccess(true);
        dataRes.setCode("10000");
        return dataRes;
    }

}
